package com.wyp.rabbitmq;

import com.wyp.entity.OrderInfo;
import com.wyp.entity.User;
import com.wyp.service.GoodsService;
import com.wyp.vo.GoodsVO;
import com.wyp.service.MSService;
import com.wyp.service.OrderService;
import com.wyp.utils.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: Oliver
 */
@Service
public class MQReceiver {
    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MSService MSService;

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @RabbitListener(queues = MQConfig.MS_QUEUE)
    public void receive(String message) {
        MSMesage mm = RedisService.StringToBean(message, MSMesage.class);
        User user = mm.getUser();
        long goodsId = mm.getGoodsId();

        //判断库存
        GoodsVO goods = goodsService.getGoodsVOById(goodsId);
        int stock = goods.getStockCount();
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        OrderInfo order = orderService.getOrderByUserIdAndGoodsId(user, goods);
        if (order != null) {
            return;
        }
        //减库存-下订单
        MSService.MS(user, goods);
    }

    @RabbitListener(queues = MQConfig.QUEUE)
    public void receiver(String message) {
        log.info("receive message:" + message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message) {
        log.info(" topic  queue1 message:" + message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message) {
        log.info(" topic  queue2 message:" + message);
    }

    @RabbitListener(queues = MQConfig.HEADER_QUEUE)
    public void receiveHeaderQueue(byte[] message) {
        log.info(" header  queue message:" + new String(message));
    }

}
